import { ConditionMatcher } from './condition-matcher.js';
import { ActionExecutor } from './action-executor.js';
import { ExampleRules } from './example-rules.js';

/**
 * 规则引擎
 * 整合所有规则处理模块的主引擎
 */
export class RuleEngine {
  constructor() {
    this.rules = new Map();
    this.conditionMatcher = new ConditionMatcher();
    this.actionExecutor = new ActionExecutor();
    this.isProcessing = false;
    this.processedCount = 0;
  }

  // ===========================================
  // 规则管理方法
  // ===========================================

  /**
   * 添加规则
   */
  addRule(rule) {
    this.rules.set(rule.id, rule);
    console.log(`📋 添加规则: ${rule.name}`);
  }

  /**
   * 移除规则
   */
  removeRule(ruleId) {
    const rule = this.rules.get(ruleId);
    if (rule) {
      this.rules.delete(ruleId);
      console.log(`📋 移除规则: ${rule.name}`);
      return true;
    }
    return false;
  }

  /**
   * 更新规则
   */
  updateRule(rule) {
    if (this.rules.has(rule.id)) {
      this.rules.set(rule.id, rule);
      console.log(`📋 更新规则: ${rule.name}`);
      return true;
    }
    return false;
  }

  /**
   * 获取所有规则
   */
  getRules() {
    return Array.from(this.rules.values());
  }

  /**
   * 获取启用的规则
   */
  getEnabledRules() {
    return Array.from(this.rules.values()).filter(rule => rule.enabled);
  }

  /**
   * 获取规则数量统计
   */
  getRuleStats() {
    const allRules = this.getRules();
    const enabledRules = allRules.filter(rule => rule.enabled);
    
    return {
      total: allRules.length,
      enabled: enabledRules.length,
      disabled: allRules.length - enabledRules.length,
      processed: this.processedCount
    };
  }

  // ===========================================
  // 规则处理方法
  // ===========================================

  /**
   * 处理事务，执行规则匹配
   */
  async processTransaction(transaction) {
    if (this.isProcessing) {
      console.log('📋 规则引擎正在处理其他事务，跳过...');
      return;
    }

    this.isProcessing = true;
    
    try {
      const activeRules = this.getEnabledRules();
      
      if (activeRules.length === 0) {
        console.log('📋 没有启用的规则');
        return;
      }
      
      console.log(`🔍 开始规则匹配: ${transaction.request.method} ${transaction.request.url}`);
      console.log(`📋 活跃规则数量: ${activeRules.length}`);
      
      const results = [];
      
      for (const rule of activeRules) {
        try {
          console.log(`🔍 检查规则: ${rule.name}`);
          
          const isMatch = await this.conditionMatcher.matchRule(rule, transaction);
          
          if (isMatch) {
            console.log(`🎯 规则匹配成功: ${rule.name} -> ${transaction.request.url}`);
            const actionResults = await this.actionExecutor.executeRuleActions(rule, transaction);
            results.push({ rule: rule.name, matched: true, actions: actionResults });
          } else {
            console.log(`❌ 规则匹配失败: ${rule.name}`);
            results.push({ rule: rule.name, matched: false });
          }
        } catch (error) {
          console.error(`❌ 处理规则失败 (${rule.name}):`, error);
          results.push({ rule: rule.name, matched: false, error: error.message });
        }
      }
      
      this.processedCount++;
      console.log(`✅ 规则处理完成，匹配结果:`, results);
      
    } finally {
      this.isProcessing = false;
    }
  }

  // ===========================================
  // 规则验证方法
  // ===========================================

  /**
   * 验证规则配置
   */
  validateRule(rule) {
    const errors = [];
    
    if (!rule) {
      errors.push('规则不能为空');
      return errors;
    }
    
    if (!rule.id) {
      errors.push('规则ID不能为空');
    }
    
    if (!rule.name) {
      errors.push('规则名称不能为空');
    }
    
    // 验证条件
    if (rule.conditions && rule.conditions.length > 0) {
      for (let i = 0; i < rule.conditions.length; i++) {
        const condition = rule.conditions[i];
        const conditionErrors = this.conditionMatcher.validateCondition(condition);
        
        if (conditionErrors.length > 0) {
          errors.push(`条件 ${i + 1}: ${conditionErrors.join(', ')}`);
        }
      }
    }
    
    // 验证动作
    const actionErrors = this.actionExecutor.validateRuleActions(rule);
    errors.push(...actionErrors);
    
    return errors;
  }

  /**
   * 验证所有规则
   */
  validateAllRules() {
    const results = [];
    
    for (const rule of this.rules.values()) {
      const errors = this.validateRule(rule);
      results.push({
        ruleId: rule.id,
        ruleName: rule.name,
        isValid: errors.length === 0,
        errors: errors
      });
    }
    
    return results;
  }

  // ===========================================
  // 示例规则方法
  // ===========================================

  /**
   * 创建示例规则
   */
  createExampleRules() {
    const examples = ExampleRules.createExampleRules();
    examples.forEach(rule => this.addRule(rule));
    console.log(`📋 已创建 ${examples.length} 个示例规则`);
    return examples;
  }

  /**
   * 获取示例规则信息
   */
  getExampleRulesInfo() {
    return ExampleRules.getExampleRulesInfo();
  }

  // ===========================================
  // 批量操作方法
  // ===========================================

  /**
   * 批量添加规则
   */
  addRules(rules) {
    const results = [];
    
    for (const rule of rules) {
      try {
        const errors = this.validateRule(rule);
        if (errors.length === 0) {
          this.addRule(rule);
          results.push({ ruleId: rule.id, status: 'success' });
        } else {
          results.push({ ruleId: rule.id, status: 'error', errors });
        }
      } catch (error) {
        results.push({ ruleId: rule.id || 'unknown', status: 'error', error: error.message });
      }
    }
    
    return results;
  }

  /**
   * 清空所有规则
   */
  clearRules() {
    const count = this.rules.size;
    this.rules.clear();
    console.log(`📋 已清空 ${count} 个规则`);
    return count;
  }

  /**
   * 启用/禁用所有规则
   */
  toggleAllRules(enabled) {
    let count = 0;
    
    for (const rule of this.rules.values()) {
      rule.enabled = enabled;
      rule.updatedAt = Date.now();
      count++;
    }
    
    console.log(`📋 已${enabled ? '启用' : '禁用'} ${count} 个规则`);
    return count;
  }

  // ===========================================
  // 配置方法
  // ===========================================

  /**
   * 设置脚本执行超时
   */
  setScriptTimeout(timeout) {
    this.actionExecutor.setScriptTimeout(timeout);
  }

  /**
   * 获取引擎状态
   */
  getStatus() {
    return {
      isProcessing: this.isProcessing,
      processedCount: this.processedCount,
      rulesCount: this.rules.size,
      enabledRulesCount: this.getEnabledRules().length,
      supportedOperators: this.conditionMatcher.getSupportedOperators(),
      supportedActionTypes: this.actionExecutor.getSupportedActionTypes()
    };
  }

  /**
   * 重置处理计数器
   */
  resetProcessedCount() {
    this.processedCount = 0;
  }
} 